/**
 * @file index.js
 * @author swan
 */
import {
    debounce,
    showToast,
    checkIsiPhoneX
} from './utils/utils';
import {articleInfo, followInfo} from './utils/mock';

/* global Page, swan, getCurrentPages */

/* eslint-disable babel/new-cap */
Page({
/* eslint-enable babel/new-cap */
    data: {
        theme: 'loadingStatus',
        loadingStatus: {
            loading: true
        },
        articleId: '', // 文章唯一标志
        title: '', // 文章标题
        avator: '', // 作者头像地址
        author: '', // 作者名
        authorId: '', // 作者的用户唯一标志
        date: '', // 发表日期
        btnLoading: false, // 按钮加载态
        content: [], // 文章正文
        imgList: [], // 文章内图片列表
        showTopBtn: false, // 是否显示回到顶部按钮
        showPageStatus: true, // 是否显示页面状态
        loading: true, // 是否加载中
        loadingBtn: false, // 是否显示重新加载按钮
        loadingTitle: '网络不给力，请稍后重试', // 页面状态提示文案
        loadingIcon: 'content', // 页面状态图标 content/wifi
        yPosition: 0,
        headerHeight: 0,
        scrollTop: 0,
        keywords: '',
        description: '',
        // 底部互动 bar 的配置
        toolbarConfig: {
            // 若 moduleList 中配置有 share 模块，默认是有，则该属性为必填，title 必传
            share: {
                title: '智能小程序，智能连接人与信息、人与服务、人与万物的开放生态'
            }
        }
    },
    onShow: function() {
        // 获取当前小程序的页面栈
        let pages = getCurrentPages();
        // 数组中索引最大的页面--当前页面
        let currentPage = pages[pages.length - 1];
        // 打印出当前页面中的 options
        console.log(currentPage.options);
        swan.setPageInfo({
            title: this.data.title,
            keywords: swan.getEnvInfoSync().appName + ',' + this.data.author +','+ this.data.keywords,
            description: this.data.description,
            releaseDate: this.data.date,
            articleTitle: this.data.title,
            image: this.data.imgList.length > 3 ? this.data.imgList.splice(0, 3)
                : (this.data.imgList.length > 0 ? this.data.imgList[0] : '')
        });
    },
    onLoad(options) {
        swan.request.mock = function (param) {
            setTimeout(() => {
                if (param.res && param.success) {
                    param.success(param.res);
                }
                else if (param.fail) {
                    param.fail({
                        errMsg: '未知错误'
                    });
                }

                param.complete && param.complete();
            }, 300);
        };
        swan.setStorageSync('@content-detail:userId', 'xxx');
        checkIsiPhoneX(this);
        this.setData({
            articleId: options.id
        });
        this.getArticleDetail(options.id, () => {
            this.setData('imgList', this.data.content.reduce((result, item) => {
                if (item.type === 'img') {
                    result.push(item.content);
                }

                return result;
            }, []));
            const query = swan.createSelectorQuery().in(this);
            query.select('.content-container').boundingClientRect();
            query.exec(info => {
                this.data.headerHeight = info[0] ? info[0].top : 0;
            });
        });
    },
    onShareAppMessage() {
        let currentPages = getCurrentPages();
        return {
            title: this.data.title,
            content: this.getDesp(),
            imageUrl: this.data.imgList.length > 0 ? this.data.imgList[0] : '',
            path: currentPages[currentPages.length - 1].privateProperties.accessUri,
            success: res => {
                if (res.result) {
                    showToast(2);
                }

            }
        };
    },
    reloadPage() {
        this.setData({
            loading: true,
            showPageStatus: true
        });
        this.onLoad({
            articleId: this.data.articleId
        });
    },
    getArticleDetail(articleId, cb) {
        swan.request({
            url: 'https://host.com/api/index/'+articleId,
            method: 'GET',
            header: {
                'content-type': 'application/json'
            },
            res: articleInfo,
            success: res => {
                console.log(res);
                var snid = 'AT' + articleId, path = '/pages/show/index?id=' + articleId;
                this.setData({
                    title: res.data.title,
                    keywords: res.data.keywords,
                    description: res.data.description,
                    avator: 'https://mbs1.bdstatic.com/searchbox/mappconsole/image/20230422/18674987-6911-4af0-8a2a-34e3f51b5360.png',
                    author: '唯美资讯',
                    authorId: 1,
                    date: res.data.updated_at,
                    content: res.data.extend,
                    toolbarConfig: {
                        share: {
                            title: res.data.title
                        }
                    },
                    loadingStatus: {
                        loading: false
                    }
                }, () => {
                    this.setData({
                        loading: false,
                        showPageStatus: false
                    });
                    swan.reportAnalytics('articleshow', {
                        articleId: this.data.articleId,
                        userId: this.data.authorId
                    });
                    cb && cb();
                });
                swan.setPageInfo({
                    title: res.data.title,
                    keywords: res.data.keywords,
                    description: res.data.description,
                    success: res => {
                        console.log('setPageInfo success');
                    },
                    fail: err => {
                        console.log('setPageInfo fail', err);
                    }
                });
            },
            fail: err => {
                this.setData({
                    loading: false,
                    loadingBtn: true,
                    loadingIcon: 'wifi',
                    loadingTitle: '网络不给力，请稍后重试'
                });
            }
        });
    },
    getDesp() {
        return this.data.content.reduce((result, item) => {
                if (item.type === 'p') {
                    result += item.content;
                }

                return result;
            }, '').substr(0, 20) + '...';
    },
    showTopBtn() {
        this.setData({
            showTopBtn: true
        });
    },
    hideTopBtn() {
        this.setData({
            showTopBtn: false
        });
    },
    tapuser({currentTarget}) {
        let userId = currentTarget.dataset.userId;
        swan.reportAnalytics('tapuser', {
            articleId: this.data.articleId,
            userId: userId
        });
        // TODO: 点击用户事件处理，通常是跳转到用户详情页
        // swan.navigateTo({
        //     url: `/user-detail/user-detail?userId=${userId}`
        // });
    },
    tapimg(e) {
        this.previewImage(e);
    },
    longtapimg(e) {
        swan.showActionSheet({
            itemList: ['查看图片', '保存到相册'],
            itemColor: '#000',
            success: res => {
                switch (res.tapIndex + 1) {
                    case 1:
                        this.previewImage(e);
                        break;
                    case 2:
                        this.saveImage(e);
                        break;
                }
            }
        });
    },
    previewImage(e) {
        swan.reportAnalytics('tapimg', {
            articleId: this.data.articleId,
            userId: this.data.authorId,
            img: e.target.dataset.src
        });
        swan.previewImage({
            current: e.target.dataset.src,
            urls: this.data.imgList
        });
    },
    saveImage(e) {
        swan.showLoading({
            title: '正在加载...'
        });
        swan.downloadFile({
            url: e.target.dataset.src,
            success: res => {
                let filePath = res.tempFilePath;
                swan.saveImageToPhotosAlbum({
                    filePath,
                    success: res => {
                        swan.reportAnalytics('saveimg', {
                            articleId: this.data.articleId,
                            userId: this.data.authorId,
                            img: e.target.dataset.src
                        });
                        swan.hideLoading();
                        showToast(5);
                    },
                    fail: err => {
                        swan.hideLoading();
                        showToast(6);
                    }
                });
            },
            fail: err => {
                swan.hideLoading();
                showToast(6);
            }
        });
    },
    touchstart(e) {
        this.data.yPosition = e.touches[0].clientY;
    },
    onPageScroll(e) {
        const query = swan.createSelectorQuery().in(this);
        query.select('.content-container').boundingClientRect();
        query.exec(info => {
            if (this.data.headerHeight - info[0].top < 10) {
                this.hideTopBtn();
            }

        });
    },
    scrollPage(e) {
        const yPosition = this.data.yPosition;
        const currentPosition = e.changedTouches[0].clientY;
        this.data.yPosition = currentPosition;
        const query = swan.createSelectorQuery().in(this);
        query.select('.content-container').boundingClientRect();
        query.exec(info => {
            if (currentPosition > yPosition && info[0].top < this.data.headerHeight) {
                this.showTopBtn();
                debounce(() => {
                    this.hideTopBtn();
                }, 2000)();
            }
            else if (yPosition - currentPosition > 10) {
                this.hideTopBtn();
            }

        });
    },
    backToTop() {
        swan.reportAnalytics('backtotop', {
            articleId: this.data.articleId,
            userId: this.data.authorId
        });
        swan.pageScrollTo({
            scrollTop: 0
        });
        this.hideTopBtn();
    },
    listener: function (e) {
        swan.redirectTo({
            url: '/extensions/component/smt-feed-page/smt-feed-page'
        });
    },
    onReady() {
        // 用于实现页面间的跳转
        requireDynamicLib('interactionLib').listenEvent();
    },
    clickComment(e) {
        const srid = e.data.srid;
        this.setData({
            detailPath: './comment-detail/comment-detail?srid=' + srid
        });
    }
});
